package com.lil.shiro.realm;

import java.util.Set;

import com.lil.shiro.model.Menu;
import com.lil.shiro.model.Role;
import com.lil.shiro.model.User;
import com.lil.shiro.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class MyShiroRealm extends AuthorizingRealm {

    @Autowired
    private UserService sysUserService;

    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        log.info(" --------- 执行 Shiro授权 --------- ");
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        User userInfo = (User) principals.getPrimaryPrincipal();
        log.info(" ------Shiro授权---" +  principals.getPrimaryPrincipal() + "--------- ");
        userInfo = sysUserService.findUserInfo(userInfo.getUserId());
        Set<Role> roles = userInfo.getRoles();
        for (Role sysRole : roles) {
            authorizationInfo.addRole(sysRole.getRoleName());
            log.info(" ---------" + sysRole.getRoleName() + "--------- ");
            Set<Menu> menus = sysRole.getMenus();
            for (Menu menu : menus) {
                authorizationInfo.addStringPermission(menu.getPermission());
                log.info(" ---------" + menu.getPermission() + "--------- ");
            }
        }
        return authorizationInfo;
    }

    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
        log.info(" --------- 执行 Shiro认证 --------- ");
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        String loginName = token.getUsername();
        // 获取数据库中对应的用户信息
        User userInfo = sysUserService.findUserInfo(loginName);
        if (userInfo == null)
            return null;

        log.info("------" + userInfo.getPassword() + "------");
        SimpleAuthenticationInfo authenticationInfo
                = new SimpleAuthenticationInfo(
                userInfo,
                userInfo.getPassword(),
//                ByteSource.Util.bytes(userInfo.getCredentialsSalt()),
                this.getName()
        );
        return authenticationInfo;
    }

}
